package com.woniu.gf.pawn.management.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.woniu.gf.pawn.comm.core.domain.*;
import com.woniu.gf.pawn.comm.core.dto.ResultDto;
import com.woniu.gf.pawn.comm.core.exception.PawnExceptionCode;
import com.woniu.gf.pawn.management.dto.SelectManagementByRoleIdDto;
import com.woniu.gf.pawn.management.dto.SelectPermissionByRoleIdDto;
import com.woniu.gf.pawn.management.param.*;
import com.woniu.gf.pawn.management.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lucas
 * @since 2020-10-13
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色")
@CrossOrigin
public class RoleController {
    @Autowired
    private ManagementService managementService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ManagementRoleService managementRoleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionService rolePermissionService;

    /**
    *@Description:  新增角色
    *@return:
    */
    @PostMapping("/addRole")
    @ApiOperation("新增角色")
    public ResultDto addRole(@RequestBody @Valid AddRoleParam addRoleParam){
        QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role_name",addRoleParam.getRoleName());
        int count = roleService.count(queryWrapper);
        if(count !=0){
            return ResultDto.fail(PawnExceptionCode.ROLE_NAME_EXIST.getCode(),PawnExceptionCode.ROLE_NAME_EXIST.getMsg());
        }
        Role role = new Role();
        BeanUtils.copyProperties(addRoleParam,role);
        roleService.save(role);
        return ResultDto.success(200,"新增角色成功");
    }

    /**
    *@Description: 根据角色id查询拥有该角色的管理员集合
    *@return:
    */
    @GetMapping("/selectManagementByRoleId")
    @ApiOperation("根据角色id查询拥有该角色的管理员集合")
    public ResultDto selectManagementByRoleId(@Valid SelectManagementByRoleIdParam selectManagementByRoleIdParam){
        System.out.println(selectManagementByRoleIdParam);
        List<Management> managements=roleService.selectManagementByRoleId(selectManagementByRoleIdParam);
        return getResultDto(managements);
    }
    /**
    *@Description: 根据角色id查询未拥有该角色的管理员集合
    *@return:
    */
    @GetMapping("/selectManagementNotRoleByRoleId")
    @ApiOperation("根据角色id查询未拥有该角色的管理员集合")
    public ResultDto selectManagementNotRoleByRoleId(@Valid SelectManagementByRoleIdParam selectManagementByRoleIdParam){
        System.out.println(selectManagementByRoleIdParam);
        List<Management> managements=roleService.selectManagementNotRoleByRoleId(selectManagementByRoleIdParam);
        return getResultDto(managements);
    }

    /**
    *@Description: 参数转换
    *@return:
    */
    private ResultDto getResultDto(List<Management> managements) {
        if(managements==null || managements.size()==0 ||managements.get(0)==null){
            return ResultDto.success(200,"查询成功");
        }
        List<SelectManagementByRoleIdDto> roleIdDtoList=new ArrayList<>();
        for(Management management:managements){
            SelectManagementByRoleIdDto roleIdDto = new SelectManagementByRoleIdDto();
            BeanUtils.copyProperties(management,roleIdDto);
            roleIdDtoList.add(roleIdDto);
        }
        return ResultDto.success(200,"查询成功",roleIdDtoList);
    }

    /**
    *@Description: 将角色分配给用户
    *@return:
    */
    @PostMapping("/allotRoleByRoleId")
    @Transactional
    @ApiOperation("将角色分配给用户")
    public ResultDto allotRoleByRoleId(@RequestBody @Valid AllotRoleParam allotRoleParam){
        QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role_id",allotRoleParam.getRoleId());
        int count = roleService.count(queryWrapper);
        if (count==0){
            return ResultDto.fail(PawnExceptionCode.ROLE_ID_NONENTITY.getCode(),PawnExceptionCode.ROLE_ID_NONENTITY.getMsg());
        }
        List<Integer> managementIdList = allotRoleParam.getManagementIdList();
        if(managementIdList !=null){
            //考虑传入的用户id不存在
            List<Management> managements =(List) managementService.listByIds(allotRoleParam.getManagementIdList());
            if(managements.size() !=managementIdList.size()){
                return ResultDto.fail(PawnExceptionCode.USER_NONENTITY.getCode(),PawnExceptionCode.USER_NONENTITY.getMsg());
            }
        }
        // 1、根据角色id 删除以前的角色用户中间表内容
        roleService.deleteManagementRoleByRoleId(allotRoleParam.getRoleId());
        // 2、根据角色id和用户id集合新增角色用户中间表
        int roleId = allotRoleParam.getRoleId();
        if(managementIdList ==null){
            return ResultDto.success(200,"分配角色成功");
        }
        List<ManagementRole> managementRoles=new ArrayList<>();
        for(Integer managementId:managementIdList){
            ManagementRole managementRole = new ManagementRole();
            managementRole.setManagementId(managementId);
            managementRole.setRoleId(roleId);
            managementRoles.add(managementRole);
        }
        managementRoleService.saveBatch(managementRoles);
        return ResultDto.success(200,"分配角色成功");
    }
    /**
    *@Description: 查询所有角色
    *@return:
    */
    @GetMapping("/selectPageRole")
    @ApiOperation("查询所有角色")
    public ResultDto selectPageRole(@Valid SelectRoleParam selectRoleParam){
        IPage<Role> roleIPage=roleService.selectPageRole(selectRoleParam);
        return ResultDto.success(200,"查询角色成功",roleIPage);
    }

    /**
     *@Description: 根据角色id查询该角色的权限集合
     *@return:
     */
    @PostMapping("/selectPermissionByRoleId")
    @ApiOperation("根据角色id查询该角色的权限集合")
    public ResultDto selectPermissionByRoleId(@RequestBody @Valid SelectPermissionByRoleIdParam selectPermissionByRoleIdParam){
        List<Permission> permissions=roleService.selectPermissionByRoleId(selectPermissionByRoleIdParam);
        return getPermissionResultDto(permissions);
    }
    
    /**
     *@Description: 根据角色id查询该角色的未拥有权限集合
     *@return:
     */
    @GetMapping("/selectPermissionNotByRoleId")
    @ApiOperation("根据角色id查询该角色的未拥有权限集合")
    public ResultDto selectPermissionNotByRoleId(@Valid SelectPermissionByRoleIdParam selectPermissionByRoleIdParam){
        List<Permission> permissions=roleService.selectPermissionNotByRoleId(selectPermissionByRoleIdParam);
        return getPermissionResultDto(permissions);
    }

    private ResultDto getPermissionResultDto(List<Permission> permissions) {
        if(permissions.get(0)==null){
            return ResultDto.success(200,"查询成功");
        }
        List<SelectPermissionByRoleIdDto> permissionByRoleIdDtoList=new ArrayList<>();
        for(Permission permission:permissions){
            SelectPermissionByRoleIdDto selectPermissionByRoleIdDto = new SelectPermissionByRoleIdDto();
            BeanUtils.copyProperties(permission,selectPermissionByRoleIdDto);
            permissionByRoleIdDtoList.add(selectPermissionByRoleIdDto);
        }
        return ResultDto.success(200,"查询成功",permissionByRoleIdDtoList);
    }


    /**
    *@Description: 修改角色权限
    *@return:
    */
    @PutMapping("/alterRolePermission")
    @Transactional
    @ApiOperation("修改角色权限")
    public ResultDto alterRolePermission(@RequestBody @Valid AlterRolePermissionParam alterRolePermissionParam){
        QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role_id",alterRolePermissionParam.getRoleId());
        int count = roleService.count(queryWrapper);
        if (count==0){
            return ResultDto.fail(PawnExceptionCode.ROLE_ID_NONENTITY.getCode(),PawnExceptionCode.ROLE_ID_NONENTITY.getMsg());
        }
        List<Integer> permissionIdList = alterRolePermissionParam.getPermissionIdList();
        if(permissionIdList !=null){
            List<Permission> permissions = (List)permissionService.listByIds(permissionIdList);
            if(permissions.size() !=permissionIdList.size()){
                return ResultDto.fail(PawnExceptionCode.PERMISSION_ID_NONENTITY.getCode(),PawnExceptionCode.PERMISSION_ID_NONENTITY.getMsg());
            }
        }
        int roleId = alterRolePermissionParam.getRoleId();
        // 1、根据角色id 删除以前的角色权限中间表内容
        roleService.deleteRolePermissionByRoleId(roleId);
        if(permissionIdList==null){
            return ResultDto.success(200,"修改角色权限成功");
        }
        // 2、根据角色id和权限id集合新增角色权限中间表
        List<RolePermission> rolePermissions=new ArrayList<>();
        for(Integer permissionId:permissionIdList){
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissions.add(rolePermission);
        }
        rolePermissionService.saveBatch(rolePermissions);
        return ResultDto.success(200,"修改角色权限成功");
    }

}

